{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a href=\"https://colab.research.google.com/github/run-llama/llama_cloud_services/blob/main/examples/parse/parsing_instructions.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n",
    "\n",
    "# Parsing documents with Instructions\n",
    "\n",
    "Parsing instructions allow you to guide our parsing model in the same way you would instruct an LLM.\n",
    "\n",
    "These instructions can be useful for improving the parser's performance on complex document layouts, extracting data in a specific format, or transforming the document in other ways.\n",
    "\n",
    "Status:\n",
    "| Last Executed | Version | State      |\n",
    "|---------------|---------|------------|\n",
    "| Aug-20-2025   | 0.6.61  | Maintained |\n",
    "\n",
    "### Why This Matters:\n",
    "Traditional document parsing can be rigid and error-prone, often missing crucial context and nuances in complex layouts. Our instruction-based parsing allows you to:\n",
    "\n",
    "1. Extract specific information with pinpoint accuracy\n",
    "2. Handle complex document layouts with ease\n",
    "3. Transform unstructured data into structured formats effortlessly\n",
    "4. Save hours of manual data entry and verification\n",
    "5. Reduce errors in document processing workflows\n",
    "\n",
    "In this demonstration, we showcase how parsing instructions can be used to extract specific information from unstructured documents. Using a McDonald's Receipt, we show how to ignore parts of the document and only parse the price of each order and the final amount to be paid."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Installation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install llama-cloud-services"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Setup API Key"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"LLAMA_CLOUD_API_KEY\"] = \"llx-...\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### McDonald's Receipt\n",
    "\n",
    "Here we extract the price of each order and the final amount to be paid."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"mcdonalds_receipt.png\" alt=\"Alt Text\" width=\"500\">"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Started parsing the file under job_id 31862c97-ac1b-46ed-b5b7-42ca4d0ffe70\n",
      "\n",
      "# McDonald's Receipt\n",
      "\n",
      "> Rate us HIGHLY SATISFIED and  \n",
      "> Receive ONE FREE ITEM  \n",
      "> Purchase any sandwich and receive an  \n",
      "> item of equal or lesser value  \n",
      "> Go to www.mcdvoice.com within 7 days  \n",
      "> and tell us about your visit.  \n",
      "> Validation Code:  \n",
      "> Expires 30 days after receipt date.  \n",
      "> Valid at participating US McDonald's.  \n",
      "\n",
      "**Survey Code:**  \n",
      "31278-01121-21018-20481-00081-0  \n",
      "\n",
      "**McDonald's Restaurant #31278**  \n",
      "2378 PINE RD NW  \n",
      "RICE, MN 56367-9740  \n",
      "TEL# 320 393 4600  \n",
      "\n",
      "| KS#  | Date       | Time    | Order  |\n",
      "|------|------------|---------|--------|\n",
      "| 1    | 12/08/2022 | 08:48 PM| 12     |\n",
      "\n",
      "| Item                     | Price |\n",
      "|--------------------------|-------|\n",
      "| 1 Happy Meal 6 Pc        | 4.89  |\n",
      "| - Creamy Ranch Cup       |       |\n",
      "| - Extra Kids Fry         |       |\n",
      "| - Wreck It Ralph 2       |       |\n",
      "| - S Coke                 |       |\n",
      "| 1 Snack Oreo McFlurry    | 2.69  |\n",
      "\n",
      "| Subtotal                 | 7.58  |\n",
      "| Tax                      | 0.52  |\n",
      "| Take-Out Total           | 8.10  |\n",
      "| Cash Tendered            | 10.00 |\n",
      "| Change                   | 1.90  |\n",
      "\n",
      "McDonald's Restaurant Rice  \n",
      "***NOW ACCEPTING APPLICATIONS***  \n",
      "text to #36453  \n",
      "apply31278  \n",
      "\n"
     ]
    }
   ],
   "source": [
    "from llama_cloud_services import LlamaParse\n",
    "\n",
    "vanilla_result = await LlamaParse(\n",
    "    parse_mode=\"parse_page_with_agent\",\n",
    "    model=\"openai-gpt-4-1-mini\",\n",
    "    high_res_ocr=True,\n",
    "    outlined_table_extraction=True,\n",
    "    output_tables_as_HTML=True,\n",
    ").aparse(\"./mcdonalds_receipt.png\")\n",
    "\n",
    "print(vanilla_result.pages[0].md)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Started parsing the file under job_id 3f4dcd5a-2ef0-4022-9bd3-a85df9ec7664\n",
      "\n",
      "* Happy Meal 6 Pc  4.89  \n",
      "  - Creamy Ranch Cup  \n",
      "  - Extra Kids Fry  \n",
      "  - Wreck It Ralph 2  \n",
      "  - S Coke  \n",
      "* Snack Oreo McFlurry  2.69  \n",
      "\n",
      "Subtotal  7.58  \n",
      "Tax  0.52  \n",
      "Take-Out Total  8.10  \n",
      "\n"
     ]
    }
   ],
   "source": [
    "parsing_instruction = \"\"\"The provided document is a McDonald's receipt. Provide ONLY each line item (item name and price) and the final amount to be paid.\"\"\"\n",
    "\n",
    "result_with_instruction = await LlamaParse(\n",
    "    parse_mode=\"parse_page_with_agent\",\n",
    "    model=\"openai-gpt-4-1-mini\",\n",
    "    high_res_ocr=True,\n",
    "    outlined_table_extraction=True,\n",
    "    output_tables_as_HTML=True,\n",
    "    # Inject the parsing instruction into the user prompt\n",
    "    user_prompt=parsing_instruction,\n",
    ").aparse(\"./mcdonalds_receipt.png\")\n",
    "\n",
    "print(result_with_instruction.pages[0].md)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
